package com.xstudio.pvzreborn.gui.container;

import com.xstudio.pvzreborn.block.entity.PVZMachineBlockEntityBase;
import com.xstudio.pvzreborn.capability.CapManager;
import com.xstudio.pvzreborn.capability.Sunshine;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.ContainerLevelAccess;
import net.minecraft.world.inventory.MenuType;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.SlotItemHandler;
import net.minecraftforge.items.wrapper.InvWrapper;

public abstract class BaseContainer<T extends PVZMachineBlockEntityBase> extends AbstractContainerMenu {

    protected final Player player;
    protected final T blockEntity;
    protected final IItemHandler inventory;

    @SuppressWarnings("unchecked")
    protected BaseContainer(int windowId, MenuType<?> menu, Inventory playerInv, BlockPos pos) {
        super(menu, windowId);
        this.player = playerInv.player;
        this.inventory = new InvWrapper(playerInv);
        this.blockEntity = (T) player.getCommandSenderWorld().getBlockEntity(pos);

        if (blockEntity != null) {
            init();
            addPlayerSlot();
        }

    }

    protected abstract void addItemSlot();

    public abstract void init();

    @Override
    public boolean stillValid(Player pPlayer) {
        return stillValid(ContainerLevelAccess.create(blockEntity.getLevel(), blockEntity.getBlockPos()), pPlayer, blockEntity.getBlockState().getBlock());
    }

    protected IItemHandler getHandler(Direction direction) {
        return blockEntity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, direction).resolve().get();
    }

    public T getBlockEntity() {
        return blockEntity;
    }

    public LazyOptional<Sunshine> getSunshineEnergy() {
	    return blockEntity.getCapability(CapManager.SUNSHINE);
    }

    private void addPlayerSlot() {
        addPlayerSlotRange(142, 0);
        addPlayerSlotRange(84, 9);
        addPlayerSlotRange(102, 18);
        addPlayerSlotRange(120, 27);
    }

    private void addPlayerSlotRange(int y, int indexOffset) {
        for (int i = 0; i < 9; i++) {
            addSlot(new SlotItemHandler(inventory, i + indexOffset, 8 + 18 * i, y));
        }
    }

}
